/// 本文件由reazhuang@outlook.com开发编写 *CodeMaid自动格式化*

using Microsoft.AspNetCore.Razor.TagHelpers;
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.Json;
using WalkingTec.Mvvm.Core.Extensions;

namespace ReaWTM.LayuiHelper
{
	[HtmlTargetElement("wt:tree", TagStructure = TagStructure.WithoutEndTag)]
	public class TreeTagHelper : BaseFieldTag
	{
		public bool ShowLine { get; set; } = true;

		/// <summary>
		/// 点击事件
		/// </summary>
		/// <summary>
		/// 点击时触发的js函数名，func(data)格式;
		/// <para>
		/// data.elem得到当前节点元素;
		/// </para>
		/// <para>
		/// data.data得到当前点击的节点数据
		/// </para>
		/// <para>
		/// data.state得到当前节点的展开状态：open、close、normal
		/// </para>
		/// </summary>
		public string ClickFunc { get; set; }

		/// <summary>
		/// 勾选事件
		/// </summary>
		/// <summary>
		/// 勾选时触发的js函数名，func(data)格式;
		/// <para>
		/// data.elem得到当前节点元素;
		/// </para>
		/// <para>
		/// data.data得到当前点击的节点数据
		/// </para>
		/// <para>
		/// data.checked是否被选中
		/// </para>
		/// </summary>
		public string CheckFunc { get; set; }
		string GetDefaultValue(bool multi)
		{
			if (Field.Model == null)
			{
				return "[]";
			}
			if (multi)
			{
				return JsonSerializer.Serialize(Field.Model, JsonOptions);
			}
			else
			{
				return $"[{JsonSerializer.Serialize(Field.Model, JsonOptions)}]";
			}
		}
		public override void Process(TagHelperContext context, TagHelperOutput output)
		{
			StringBuilder builder = new StringBuilder();
			bool MultiSelect = false;
			var type = Field.Metadata.ModelType;
			if (type.IsArray || (type.IsGenericType && typeof(List<>).IsAssignableFrom(type.GetGenericTypeDefinition())))// Array or List
			{
				MultiSelect = true;
			}


			output.TagName = "div";
			output.Attributes.Add("id", Id);
			output.TagMode = TagMode.StartTagAndEndTag;
			output.Attributes.Add("wtm-ctype", "tree");
			output.Attributes.Add("wtm-name", Field.Name);
			output.Attributes.Add("class", "wtm-tree");
			Id = string.IsNullOrEmpty(Id) ? Guid.NewGuid().ToNoSplitString() : Id;


			builder.Append($@"
<script>
wtm.tree_Render({{
id:'{Id}',
url:'{ItemUrl}',
fieldName:'{Field.Name}',
onlyIconControl:false,
showCheckbox:{GetBooleanString(MultiSelect)},
showLine:{GetBooleanString(ShowLine)},
customClick:'{ClickFunc}',
customCheck:'{CheckFunc}',
value:{GetDefaultValue(MultiSelect)}
}});
</script>
");
			output.Content.SetHtmlContent(builder.ToString());
			base.Process(context, output);
		}

		protected override void SetRequired(TagHelperOutput output)
		{
			string layverify = "required";
			if (!string.IsNullOrEmpty(LayVerify))
			{
				layverify = $"{layverify}|{LayVerify}";
			}

			output.PostElement.AppendHtml($@"<input type='hidden' lay-verify='{layverify}' id='required_{Id}'
lay-reqText='{THProgram._localizer["Validate.{0}required", Field?.Metadata?.DisplayName ?? Field?.Metadata?.Name]}'>");
		}
	}
}